package com.steven.ourcontest.team.viewmodel

import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import com.steven.ourcontest.base.BaseViewModel
import com.steven.ourcontest.chat.api.ChatApi
import com.steven.ourcontest.chat.bean.ChatOnLineRes
import com.steven.ourcontest.team.api.TeamApi
import com.steven.ourcontest.team.bean.MatchInfoRes
import com.steven.ourcontest.team.bean.TeamDetail
import com.steven.ourcontest.team.helper.TeamController
import com.steven.ourcontest.utils.plusAssign
import io.reactivex.Observable
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
import java.lang.Exception
import java.util.concurrent.TimeUnit
import kotlin.math.abs

class AddTeamViewModel : BaseViewModel() {
    private val _matchResponse = MutableLiveData<MatchInfoRes>()
    val matchResponse: LiveData<MatchInfoRes>
        get() = _matchResponse

    @Volatile
    private var lastChangeTime = 0L
    private var lastQueryId = 0L

    fun editChange(str: String) {
        lastChangeTime = System.currentTimeMillis()
        disposed += Observable.timer(1, TimeUnit.SECONDS).subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread()).subscribe({
                lastQueryId = 0L
                if (abs((System.currentTimeMillis() - lastChangeTime)) >= 800) {
                    queryMatch(str, lastQueryId)
                }
            }, {
            })
    }

    private fun queryMatch(matchName: String, lastId: Long) {
        disposed += TeamApi.instance.searchMatchList(matchName, lastId)
            .subscribe({
                _matchResponse.value = it
                lastQueryId = it.data.last().id
            }, {
                it.printStackTrace()
            })
    }

    fun queryMatchMore(matchName: String, success: () -> Unit) {
        disposed += TeamApi.instance.searchMatchList(matchName, lastQueryId)
            .subscribe({
                _matchResponse.value = it
                try {
                    success.invoke()
                } catch (e: Exception) {
                    e.printStackTrace()
                }
                lastQueryId = it.data.last().id
            }, {
                it.printStackTrace()
            })
    }

    fun createTeam(teamName: String, matchId:Long,matchName: String, url: String, success: () -> Unit) {
        disposed += TeamApi.instance.createTeam(teamName,matchId,matchName, url)
            .subscribe({
                success.invoke()
            }, {
                it.printStackTrace()
            })
    }
}